<template>
    <div class="home">
      <x-header :left-options="{showBack: false}">
        <router-link slot="left" to="/user" class="user"></router-link>
        智慧党建
        <router-link slot="right" to="/home/infos" class="message"><badge :text="tipNums" v-if="tipNums"></badge></router-link>
      </x-header>
      <v-scroll :on-infinite="infinite" :on-refresh="refresh"   ref="my_scroller" :dataList="scrollData" id="homeId">
        <div class="homeBody">
          <div class="banner">
              <div class="topBg"></div>
              <div class="banner-swiper">
                  <swiper loop auto :aspect-ratio="360/750"  :index="banner_index" @on-index-change="banner_onIndexChange">
                    <swiper-item v-for="(item,index) in banner_list" :key="index">
                      <img :src="item.src" alt="">
                    </swiper-item>
                  </swiper>
              </div>
          </div>
          <div class="childItem">
              <grid :cols="5">
                  <grid-item label="支部风采" link="/home/branch">
                      <img slot="icon" src="./home_menu_zbfc.png" alt="">
                  </grid-item>
                  <grid-item label="三会一课" link="/home/lesson?status=dynamic">
                      <img slot="icon" src="./home_menu_shyk.png" alt="">
                  </grid-item>
                  <grid-item label="走帮服" link="/home/help?status=dynamic">
                      <img slot="icon" src="./home_menu_zbf.png" alt="">
                  </grid-item>
                  <grid-item label="党费缴纳" link="/home/fees">
                      <img slot="icon" src="./home_menu_dfjn.png" alt="">
                  </grid-item>
                  <grid-item label="党员积分" link="/home/integral?status=quarter">
                      <img slot="icon" src="./home_menu_dyjf.png" alt="">
                  </grid-item>
              </grid>
          </div>
          <div class="newsList">
              <div class="list_head">党建动态</div>
              <div class="list_content"><!--//创建一个模板，从newsLists中获取数据-->
                <template v-for="(item,index) of homeNews">
                  <router-link tag="div" class="list" :to="{name: 'NewsDetail', params:{newsid:item.id}}" :key="index">
                      <div class="list_text">
                          <div class="list_title">{{item.title}}</div>
                          <div class="list_time">{{item.create_time}}</div>
                      </div>
                      <div class="list_img" v-if="item.first_thumb">
                          <img :src="item.first_thumb" alt="">
                      </div>
                  </router-link>
                </template>
              </div>
          </div>
        </div>
      </v-scroll>
    </div>
</template>

<script>
import { XHeader, Swiper, SwiperItem, Grid, GridItem, Badge } from "vux";
import { mapGetters } from "vuex";
import VScroll from "../pull-refresh";
import api from "../../api/index";
import axios from "axios";
export default {
  components: {
    XHeader,
    Swiper,
    SwiperItem,
    Grid,
    GridItem,
    Badge,
    VScroll
  },
  data() {
    return {
      userid: "",
      page: 1,
      num: 10,
      scrollData: {
        noFlag: false //暂无更多数据显示
      },
      banner_list: [
        {
          img: require("./home_bg.png")
        },
        {
          img: require("./home_bg.png")
        },
        {
          img: require("./home_bg.png")
        }
      ],
      banner_index: 0,
      homeNews: [],
      tipNums: 0,
      registrationid: ""
    };
  },
  //计算属性
  computed: {
    ...mapGetters([
      "homeList",
      "homeListTotal",
      "errorAnNewsMsg",
      "homeNewsScrollTop",
      "unNewsNums",
      "banners"
    ])
  },
  created() {},
  //
  activated() {
    console.log("init...");
    document.addEventListener("deviceready", this.onDeviceReady, false);
    document.addEventListener(
      "jpush.receiveMessage",
      this.onReceiveMessage,
      false
    );

    this.$store.dispatch("getBanners");
    this.userid = window.localStorage.getItem("user");
    this.$store.dispatch("getHomeList", { user_id: this.userid });
    this.$store.dispatch("getUnNewsTotals", { user_id: this.userid });
  },
  mounted() {
    this.$nextTick(() => {
      this.box = this.$el.querySelector("#homeId");
      this.box.addEventListener("scroll", this.handler, false);
    });
  },
  //侦听属性
  watch: {
    errorAnNewsMsg: function(value) {
      this.$vux.toast.text(value, "middle");
    },
    // homeNews: function(val) {
    //   if (this.homeListTotal <= this.num || val.length >= this.homeListTotal) {
    //     this.scrollData.noFlag = true;
    //   } else {
    //     this.scrollData.noFlag = false;
    //   }
    // },
    page: function(val) {
      let total = Math.ceil(this.homeListTotal / this.num);
      if (val > total) {
        this.scrollData.noFlag = true;
      }
    },
    homeList: function(val) {
      this.homeNews = val;
    },
    unNewsNums: function(val) {
      // this.tipNums = val;
    },
    banners: function(val) {
      this.banner_list = val;
    }
  },
  methods: {
    handler() {
      this.box = document.querySelector("#homeId");
      this.$store.dispatch("updateHomePosition", this.box.scrollTop);
    },
    banner_onIndexChange(index) {
      this.banner_index = index;
    },
    refresh(done) {
      this.$store.dispatch("getBanners");
      this.$store.dispatch("getHomeList", { user_id: this.userid });
      this.$store.dispatch("getUnNewsTotals", { user_id: this.userid });
      this.page = 1;
      done();
    },
    infinite(done) {
      this.page++;
      let end = this.num * this.page;
      let i = end - this.num;
      let more = this.$el.querySelector(".load-more");
      this.$store
        .dispatch("getHomeList", { user_id: this.userid, page: this.page })
        .then(() => {
          for (i; i < end; i++) {
            if (i >= this.homeListTotal) {
              more.style.display = "none"; //隐藏加载条
              // this.scrollData.noFlag = true;
              break;
            } else {
              more.style.display = "none"; //隐藏加载条
            }
          }
        });
      done();
    },
    onDeviceReady() {
      try {
        console.log("device ready ...");
        window.JPush.init();
        window.JPush.setDebugMode(true);
        window.setTimeout(this.getRegistrationID, 1000);

        // if (device.platform != "Android") {
        // window.JPush.setApplicationIconBadgeNumber(0);
        // }
        console.log('jpush init ok...')
      } catch (exception) {
        console.log(exception);
      }
    },
    getRegistrationID() {
      console.log('jpush get registrationid ...')
      console.log(window.JPush)
      // window.JPush.getRegistrationID(function(){console.log('get rid callback...')});
      window.JPush.getRegistrationID(this.onGetRegistrationID);
       console.log('jpush get registrationid 2...')
    },
    onGetRegistrationID(data) {
      console.log('jpush get registrationid callback ...')
      try {
        console.log("JPushPlugin:registrationID is " + data);

        console.log(data, typeof data);
        console.log(data.length);

        if (data.length == 0) {
          var t1 = window.setTimeout(this.getRegistrationID, 1000);
        } else {
          this.registrationid = data;

          var url = "http://rugao.ztemap.com:8086/api/jpush/push/register";
          var data = { register_id: data, user_id: this.userid };

          fetch(url, {
            method: "POST", // or 'PUT'
            body: JSON.stringify(data), // data can be `string` or {object}!
            headers: {
              "Content-Type": "application/json"
            }
          })
            .then(res => res.json())
            .catch(error => console.error("Error:", error))
            .then(response => console.log("Success:", response));
        }
      } catch (exception) {
        console.log(exception);
      }
    },
    onReceiveMessage(event) {
      try {
        var message;
        if (device.platform == "Android") {
          message = event.message;
        } else {
          message = event.content;
        }
        // $("#messageResult").html(message);

        this.tipNums = JSON.parse(message).count;
        // console.log(message)
      } catch (exception) {
        console.log("JPushPlugin:onReceiveMessage-->" + exception);
      }
    }
  }
};
</script>

<style lang="less">
.home {
  font-size: 0;
  height: 100%;
  position: relative;
  .vux-header {
    .user {
      display: inline-block;
      width: 1.375rem;
      height: 1.375rem;
      background: url("home_menu_user.png") no-repeat;
      background-size: 100% 100%;
    }
    .message {
      display: inline-block;
      width: 1.375rem;
      height: 1.375rem;
      background: url("home_menu_mes.png") no-repeat;
      background-size: 100% 100%;
    }
    .vux-badge {
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: -8px;
      right: -6px;
      border: 1px solid #fff;
    }
  }
  .banner {
    width: 100%;
    height: 11.3125rem;
    position: relative;
    .topBg {
      height: 50%;
      background: rgb(214, 60, 50);
    }
    .banner-swiper {
      width: 22.5rem;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0.46875rem;
      border-radius: 0.625rem;
      overflow: hidden;
      img {
        width: 100%;
      }
      .vux-swiper {
        border-radius: 0.625rem;
      }
    }
  }
  .childItem {
    padding: 1.0625rem 0 1.125rem;
    .weui-grids {
      padding: 0 0 0.4375rem;
      border-bottom: 1px solid rgb(237, 238, 240);
      &:before,
      &:after {
        display: none;
      }
      .weui-grid {
        padding: 0;
        &::before,
        &::after {
          display: none;
        }
        &:active {
          background: transparent;
        }
      }
      .weui-grid__icon {
        width: 2.6875rem;
        height: 2.6875rem;
      }
      .weui-grid__label {
        font-size: 0.8125rem;
        color: rgb(51, 51, 51);
      }
    }
  }
  .newsList {
    width: 100%;
    padding: 0 0.75rem;
    .list_head {
      box-sizing: border-box;
      /*margin-left: .625rem;*/
      width: 100%;
      padding-left: 0.375rem;
      font-size: 1.1875rem;
      font-family: "SourceHanSansSC-Normal";
      font-weight: bold;
      color: rgb(0, 0, 0);
      border-left: 4px solid rgb(255, 0, 0);
    }
    .list_content {
      width: 100%;
      .list {
        box-sizing: border-box;
        width: 100%;
        /*padding: .25rem .75rem;*/
        padding: 0.25rem 0;
        display: flex;
        border-bottom: 1px solid rgb(237, 238, 240);
      }
      .list_img {
        width: 7rem;
        height: 3.9375rem;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .list_text {
        flex: 1;
        .list_title {
          font-size: 1.0625rem;
          font-family: "SourceHanSansSC-Normal";
          color: rgb(51, 51, 51);
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        .list_time {
          margin-top: 0.625rem;
          font-size: 0.875rem;
          font-family: "SourceHanSansSC-Regular";
          color: rgb(153, 153, 153);
        }
      }
    }
  }
}
</style>
